import { useState, useEffect } from 'react';
import { Button, Form, Input, Picker, Dialog, Toast, List, Cell } from '@nutui/nutui-react-taro';
import Taro from '@tarojs/taro';
import { getAppVersionListApi, uploadAppPackageApi, deleteAppPackageApi } from '@/api/handleAppVersion';
import './UploadFile.scss';

const UploadFile = () => {
  const [formState, setFormState] = useState({
    fileOwnership: '',
    version: '',
    file: [],
  });
  const [dataSource, setDataSource] = useState([]);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [currentItem, setCurrentItem] = useState(null);
  const [showToast, setShowToast] = useState({ show: false, msg: '', type: 'text' });

  const fileOwnershipRange = [
    { label: '一日之计', value: 'yrzj' },
    { label: '在线笔记', value: 'knoTree' },
  ];

  useEffect(() => {
    searchHistoryAppVersionList();
  }, []);

  const showNutToast = (msg, type = 'text') => {
    setShowToast({ show: true, msg, type });
    setTimeout(() => setShowToast({ show: false, msg: '', type: 'text' }), 2000);
  };

  const searchHistoryAppVersionList = async () => {
    try {
      const res = await getAppVersionListApi('');
      if (res) {
        setDataSource(res.map(item => ({
          key: item.id.toString(),
          fileOwnership: item.fileOwnership,
          fileName: item.fileName,
          version: item.version,
          remotePath: item.filePath,
          isAbandon: item.isAbandon ? '是' : '否',
        })));
      }
    } catch (error) {
      console.error('Error fetching app version list:', error);
      showNutToast('获取版本列表失败', 'fail');
    }
  };

  const handleDelete = async () => {
    if (currentItem) {
      try {
        const res = await deleteAppPackageApi({ id: currentItem.key, remotePath: currentItem.remotePath });
        if (res) {
          await searchHistoryAppVersionList();
          showNutToast('删除成功', 'success');
        } else {
          showNutToast('删除失败', 'fail');
        }
      } catch (error) {
        console.error('Error deleting app package:', error);
        showNutToast('删除失败', 'fail');
      }
    }
    setShowDeleteConfirm(false);
  };

  const handleShowDeleteConfirm = (item) => {
    setCurrentItem(item);
    setShowDeleteConfirm(true);
  };

  const handleSubmit = async (event) => {
    event.preventDefault();
    if (!formState.fileOwnership || !formState.version || formState.file.length === 0) {
      showNutToast('请填写完整信息', 'warn');
      return;
    }

    const formData = new FormData();
    formData.append('file', formState.file[0]);
    formData.append('version', formState.version);
    formData.append('fileOwnership', formState.fileOwnership);

    try {
      const res = await uploadAppPackageApi(formData);
      if (res) {
        showNutToast('上传成功', 'success');
        await searchHistoryAppVersionList();
      } else {
        showNutToast('上传失败', 'fail');
      }
    } catch (err) {
      showNutToast('上传失败', 'fail');
    }
  };

  const handleFileChange = (e) => {
    setFormState({ ...formState, file: e.target.files });
  };

  const handlePickerChange = (val) => {
    setFormState({ ...formState, fileOwnership: fileOwnershipRange[val[0]].value });
  };

  return (
    <div className='uploadFile'>
      <Toast visible={showToast.show} msg={showToast.msg} type={showToast.type} />
      <div className='pageTitle'>上传文件</div>

      <Form onSubmit={handleSubmit} footer={null}>
        <Picker
          options={fileOwnershipRange.map(item => item.label)}
          onConfirm={handlePickerChange}
        >
          {fileOwnershipRange.find(item => item.value === formState.fileOwnership)?.label || '请选择文件归属'}
        </Picker>
        <Input
          label='版本号'
          placeholder='请输入版本号'
          value={formState.version}
          onChange={value => setFormState({ ...formState, version: value })}
        />
        <div className='at-input'>
          <input type='file' onChange={handleFileChange} />
        </div>
        <Button type='primary' formType='submit'>上传</Button>
      </Form>

      <div className='historyList'>
        <List>
          {dataSource.map((item) => (
            <Cell
              key={item.key}
              title={item.fileName}
              description={`版本: ${item.version} | 归属: ${item.fileOwnership}`}
              extra={<Button size='small' type='danger' onClick={() => handleShowDeleteConfirm(item)}>删除</Button>}
            />
          ))}
        </List>
      </div>

      <Dialog
        visible={showDeleteConfirm}
        title='确认删除'
        content='确定要删除这个文件吗？'
        onCancel={() => setShowDeleteConfirm(false)}
        onConfirm={handleDelete}
        cancelText='取消'
        confirmText='确定'
      />
    </div>
  );
};

export default UploadFile;